package com.jcark.utilscode

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.SizeUtils

/**
 * Description:瀑布流(单项四周空白)分隔线 <br>
 * @author King.Zi<br>
 * @date 2022/6/17<br>
 * Email: 78688689@qq.com
 */
class StaggeredItemDecoration(
    private val hasHeader: Boolean = false,
    private val hasFooter: Boolean = false,
    private val topSpace: Float = 0f,
    private val horizontalSpace: Float = 12f,
    private val middleSpace: Float = 6f,
    private val bottomSpace: Float = 0f,
) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view)
        var spanCount = 0
        var spanIndex = 0
        val firstIndex = if (hasHeader) 1 else 0
        val adapter = parent.adapter
        val layoutManager = parent.layoutManager
        if (adapter == null || layoutManager == null) {
            return
        }
        if (layoutManager is StaggeredGridLayoutManager) {
            spanCount = layoutManager.spanCount
            spanIndex = (view.layoutParams as StaggeredGridLayoutManager.LayoutParams).spanIndex
        }
        val itemCount = if (hasFooter) adapter.itemCount - 1 else adapter.itemCount

        val dpHorizontal: Int = SizeUtils.dp2px(horizontalSpace)
        val dpMiddle: Int = SizeUtils.dp2px(middleSpace)
        val dpTop: Int = SizeUtils.dp2px(topSpace)
        val dpBottom: Int = SizeUtils.dp2px(bottomSpace)

        if (position in firstIndex until itemCount && spanCount == 2) {
            if (spanIndex != GridLayoutManager.LayoutParams.INVALID_SPAN_ID) {
                if (spanIndex % 2 == 0) {
                    //left item
                    outRect.left = dpHorizontal
                    outRect.right = dpMiddle
                } else {
                    //right item
                    outRect.left = dpMiddle
                    outRect.right = dpHorizontal
                }

                //top
                outRect.top = dpTop
                //bottom
                outRect.bottom = dpBottom
            }
        }
    }
}